﻿using Knife.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Knife.Core.DataBase
{
    public class EntityMapper
    {
         private static EntityMapper Mapping = null;
        private static object Mapping_Lock = new object();
        private Dictionary<Type, MapperEntity> StructDic { set; get; }
        public static EntityMapper GetInstance()
        {
            if (Mapping == null)
            {
                lock (Mapping_Lock)
                {
                    if (Mapping == null)
                    {
                        Mapping = new EntityMapper();
                    }
                }
            }
            return Mapping;
        }
        public EntityMapper()
        {
            this.ScanStruct();
        }
        public void ScanStruct()
        {
            if (StructDic == null)
            {
                StructDic = new Dictionary<Type, MapperEntity>();
            }
            Type BaseStrcutType = typeof(BaseEntity);
            var Assemblys = new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
            foreach (Assembly AssItem in Assemblys)
            {
                try
                {
                    List<Type> TypeList = new List<Type>(AssItem.GetTypes()).FindAll((Type type) => BaseStrcutType.IsAssignableFrom(type) && type != BaseStrcutType);
                    foreach (Type TypeItem in TypeList)
                    {
                        MapperEntity Entity = new MapperEntity(TypeItem);
                        Entity.ScanSelf();
                        StructDic.Add(TypeItem, Entity);
                    }
                }
                catch (System.Exception)
                {

                }
            }
        }
        public MapperEntity GetMapperEntity(Type @Type)
        {
            //如果时动态加载dll，这里需要进行判断，没有进行重新生成
            if (!StructDic.ContainsKey(@Type))
            {
                MapperEntity Entity = new MapperEntity(@Type);
                Entity.ScanSelf();
                StructDic.Add(@Type, Entity);
            }
            return StructDic[@Type];
        }
    }
}
